
//
//  ZZCarVC.m
//  新项目
//
//  Created by 刘耀宗 on 2016/12/19.
//  Copyright © 2016年 刘耀宗. All rights reserved.
//

#import "ZZCarVC.h"
#import "ZZCarTVCell.h"
#import "ZZCarTVModel.h"
#import "ZZCarDetailsViewController.h"

@interface ZZCarVC () <UITableViewDelegate , UITableViewDataSource>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic)  NSMutableArray *dataMArr;
@property (weak, nonatomic) IBOutlet UIButton *yuyueBut;
@property (weak, nonatomic) IBOutlet UIButton *zaichangBut;
@property (weak, nonatomic) IBOutlet UIButton *jiesuanBut;
@property (strong, nonatomic) UIColor  *selectColor;
@property (strong, nonatomic) UIColor  *nullColor;
@property (assign, nonatomic) NSInteger netPageMark;
@property (strong, nonatomic) UIAlertView *netAlert;

@property (nonatomic, strong) JHHJView *centerView;

@property (weak, nonatomic) IBOutlet UIView *secondTitleView;


@end

@implementation ZZCarVC
@synthesize dataMArr  = _dataMArr;
@synthesize selectColor = _selectColor;
@synthesize nullColor = _nullColor;
@synthesize netPageMark = _netPageMark;
@synthesize selectMark  = _selectMark;
@synthesize netAlert  = _netAlert;

- (void)dealloc {
    _dataMArr = nil;
    _selectColor = nil;
    _nullColor = nil;
}
-(JHHJView *)centerView
{
    if (_centerView == nil) {
        _centerView = [JHHJView shareInstanceJHHJViewWithFrame:CGRectMake(0, 0, newwidth, newheight)];
    }
    return _centerView;
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"进厂车辆";
    _selectColor = [UIColor colorWithRed:56/255.0 green:118/255.0 blue:193/255.0 alpha:1];
    _nullColor   = [UIColor colorWithRed:64/255.0 green:64/255.0 blue:64/255.0 alpha:1];
    _netPageMark = 1;
    [_tableView setSeparatorStyle:NO];
    // 推测高度
    self.tableView.estimatedRowHeight = 100;
    // iOS8之后默认就是如此设置
    self.tableView.rowHeight = UITableViewAutomaticDimension;

    if(!_dataMArr){
        _dataMArr = [[NSMutableArray alloc] init];
    }
    
    [self refreshAction];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    if(_dataMArr == nil || _dataMArr.count == 0){
        [self tapSecondTitleAction:_yuyueBut];
    }
}

- (void)refreshAction {
    // 下拉刷新
    self.tableView.mj_header= [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [_dataMArr removeAllObjects];
        _netPageMark = 1;
        [_tableView reloadData];
        [self factoryCarNetRequest];
    }];
    
    // 上拉刷新
    _tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        _netPageMark = _netPageMark + 1;
        [self factoryCarNetRequest];
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)tapSecondTitleAction:(id)sender {
    [_yuyueBut setTitleColor:_nullColor forState:UIControlStateNormal];
    [_zaichangBut setTitleColor:_nullColor forState:UIControlStateNormal];
    [_jiesuanBut setTitleColor:_nullColor forState:UIControlStateNormal];
    
    UIButton *tempBut = (UIButton *)sender;
    [tempBut setTitleColor:_selectColor forState:UIControlStateNormal];
    if(tempBut.tag == 4600){
        // 预约车辆
        _selectMark = 1;
        
    }else if (tempBut.tag == 4601){
        // 在厂车辆
        _selectMark = 2;

    }else if (tempBut.tag == 4602){
        // 结算车辆
        _selectMark = 3;
    }
    //[MBProgressHUD showMessage:@"请稍候..."];
      [self.centerView showLoadingOnView:self.tableView WithFrame:self.tableView.bounds];
    _netPageMark = 1;
    [_dataMArr removeAllObjects];
    [_tableView reloadData];
    [self factoryCarNetRequest];
    [_tableView setContentOffset:CGPointMake(0,0) animated:NO];
}

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataMArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"ZZCarTVCell";
    ZZCarTVCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (!cell) {
        cell = (ZZCarTVCell *)[[[NSBundle mainBundle] loadNibNamed:@"ZZCarTVCell" owner:nil options:nil] objectAtIndex:0];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        [cell setBackgroundColor:[UIColor clearColor]];
    }
    
    if(indexPath.row < _dataMArr.count){
        [cell assignmentDataWithModel:[_dataMArr objectAtIndex:indexPath.row] andSelectMark:_selectMark andRow:indexPath.row];
    }else{
        [cell assignmentDataWithModel:nil andSelectMark:_selectMark andRow:indexPath.row];
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    ZZCarTVCell *carCell = [tableView cellForRowAtIndexPath:indexPath];
    ZZCarTVModel *tvModel = carCell.dataModel;
    if(tvModel){
        ZZCarDetailsViewController *details = [[ZZCarDetailsViewController alloc] initWithNibName:@"ZZCarDetailsViewController" bundle:nil];
        PushVC(details);
    }
}

#pragma mark - 网络请求
- (void)factoryCarNetRequest {
    NSUserDefaults *loginDefaults = [NSUserDefaults standardUserDefaults];
    NSDictionary   *loginDict  = [loginDefaults objectForKey:@"loginInfo"];
    NSString *company_id = [NSString stringWithFormat:@"%ld",[[loginDict objectForKey:@"CompanyID"] integerValue]];

    NSMutableDictionary *dataDict = [[NSMutableDictionary alloc] init];
    [dataDict setObject:company_id forKey:@"companyid"];
    [dataDict setObject:[NSString stringWithFormat:@"%ld",(long)_netPageMark] forKey:@"pageIndex"];
    [dataDict setObject:LIST_CELL_NUM forKey:@"pageSize"];
    if(_selectMark == 1){       // 预约
        [dataDict setObject:@"1" forKey:@"Type"];
    }else if (_selectMark == 2){// 在厂
        [dataDict setObject:@"2" forKey:@"Type"];
    }else if (_selectMark == 2){// 结算
        [dataDict setObject:@"3" forKey:@"Type"];
    }
    NSString *postURL = @"api/CmpCarInfo/CarInfo/GetCar";
    NSString *jsonStr = [WHJSON jsonStringWithObject:dataDict];
    NSMutableDictionary *paramsDict=[NSMutableDictionary dictionary];
    [paramsDict setObject:jsonStr forKey:@"data"];
   
    [YBHttpTool post:postURL params:paramsDict success:^(NSDictionary *resultObj){
        BOOL xlRefresh = YES;
        [self.centerView hideLoading];
        if(resultObj){
            NSInteger theCode = [[resultObj objectForKey:@"code"] integerValue];
            if(theCode){
                NSDictionary *sucDict = [WHJSON objectFormJsonString:[resultObj objectForKey:@"resultJson"]];
                if(![[sucDict class] isSubclassOfClass:[NSDictionary class]]){
                    sucDict = nil;
                }
                NSInteger totalIndex  = [[sucDict objectForKey:@"total"] integerValue];
                NSArray  *resArr =  [sucDict objectForKey:@"rows"];
                NSMutableArray *dataArr = [self transformModelWithArr:resArr];
                if(dataArr && dataArr.count>0 && _netPageMark==1){
                    [_dataMArr removeAllObjects];
                }
                if(!dataArr || dataArr.count<[LIST_CELL_NUM integerValue]){
                    [_tableView.mj_footer endRefreshingWithNoMoreData];
                    xlRefresh = NO;
                }else{
                    [_tableView.mj_footer resetNoMoreData];
                }
                if(!_dataMArr){
                    _dataMArr = (NSMutableArray *)dataArr;
                }else{
                    [_dataMArr addObjectsFromArray:dataArr];
                }
            }else{
                NSString *messageStr = [resultObj objectForKey:@"message"];
                if(messageStr == nil || [messageStr isEqualToString:@""]){
                    messageStr = @"获取数据失败！";
                }
                if(!_netAlert){
                    _netAlert = [[UIAlertView alloc] initWithTitle:nil message:messageStr delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                }
                _netAlert.message = messageStr;
                [_netAlert show];
            }
        }else{
            NSString *messageStr = @"获取数据失败！";
            if(!_netAlert){
                _netAlert = [[UIAlertView alloc] initWithTitle:nil message:messageStr delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            }
            _netAlert.message = messageStr;
            [_netAlert show];
        }
        
        [MBProgressHUD hideHUD];
        [_tableView.mj_header endRefreshing];
        if(xlRefresh){
            [_tableView.mj_footer endRefreshing];
        }
        [_tableView reloadData];
        if(_dataMArr == nil || _dataMArr.count == 0){
            [self creatNoDataViewAction:1];
            [self.view bringSubviewToFront:_secondTitleView];
        }else{
            [self removeNoDataViewAction];
        }
        
    } failure:^(NSError *error){
        [MBProgressHUD hideHUD];
        [_tableView.mj_header endRefreshing];
        [_tableView.mj_footer endRefreshing];
        [_tableView reloadData];
        
        NSString *messageStr = @"网络请求失败！";
        NSInteger errorCode = error.code;
        if(errorCode == -1009){
            [self creatNoDataViewAction:2];
            [self.view bringSubviewToFront:_secondTitleView];
            messageStr = @"已断开与互联网的连接！";
            
        }else if(errorCode == -1001){
            messageStr = @"网络请求超时，请切换到流畅的网络环境下使用。";
            
        }else{
            if(_dataMArr == nil || _dataMArr.count == 0){
                [self creatNoDataViewAction:1];
                [self.view bringSubviewToFront:_secondTitleView];
            }
        }
        if(!_netAlert){
            _netAlert = [[UIAlertView alloc] initWithTitle:nil message:messageStr delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        }
        _netAlert.message = messageStr;
        [_netAlert show];
    }];
}

// 返回字典数组->保养维修model数组
- (NSMutableArray *)transformModelWithArr:(NSArray *)theReturnArr {
    NSMutableArray *tempMArr = [[NSMutableArray alloc] init];
    for (int i = 0; i < theReturnArr.count ; i ++) {
        NSDictionary *tempDict = [theReturnArr objectAtIndex:i];
        NSString *str = @"";
        ZZCarTVModel *carModel = [[ZZCarTVModel alloc] init];
        carModel.mID    = [DMToolsObject changeNullDataWith:[tempDict objectForKey:@"ID"] andDefault:str];
        carModel.mTitle = [DMToolsObject changeNullDataWith:[tempDict objectForKey:@"Type"] andDefault:str];
        carModel.mUserName = [DMToolsObject changeNullDataWith:[tempDict objectForKey:@"CarOwner"] andDefault:str];
        carModel.mPhone    = [DMToolsObject changeNullDataWith:[tempDict objectForKey:@"CarOwnerTel"] andDefault:str];
        carModel.mCarModel = [DMToolsObject changeNullDataWith:[tempDict objectForKey:@"TypeName"] andDefault:str];
        carModel.mCarNumber= [DMToolsObject changeNullDataWith:[tempDict objectForKey:@"PlateNumber"] andDefault:str];
        NSString *strRepair= [DMToolsObject changeNullDataWith:[tempDict objectForKey:@"RepairsTime"] andDefault:str];
        carModel.mRepairTime  = [DMToolsObject getTimestampWithStringTime:strRepair];
        NSString *strClear = [DMToolsObject changeNullDataWith:[tempDict objectForKey:@"ClearingTime"] andDefault:str];
        carModel.mClearTime   = [DMToolsObject getTimestampWithStringTime:strClear];
        NSString *priceStr = [NSString stringWithFormat:@"%.2f",[[tempDict objectForKey:@"Price"] floatValue]];
        carModel.mPrice = [DMToolsObject changeNullDataWith:priceStr andDefault:str];
        carModel.mType  = [DMToolsObject judgeDataTypeFrom:carModel.mTitle];
        [tempMArr addObject:carModel];
    }
    return tempMArr;
}

#pragma mark DMNoDataDelegate
- (void)noDataTapAction:(NSInteger )theMark {
    if(theMark == 2){
        // 暂无网络 点击再试试
        [MBProgressHUD showMessage:@"请稍候..."];
        _netPageMark = 1;
        [_dataMArr removeAllObjects];
        [_tableView reloadData];
        [self factoryCarNetRequest];
        [_tableView setContentOffset:CGPointMake(0,0) animated:NO];
    }
}

@end
